/*
 * dsm_terminator.cpp
 *
 *  Created on: Dec 15, 2013
 *      Author: m
 */

#include <cstdlib>
#include <fstream>
#include "DSMComun.h"
#include "SharedMemory2.h"
#include "MessageQueue.h"
#include "Semaphore.h"
#include "Sequence.h"
#include "ColaRemotaTransmisor.h"
#include "ColaRemotaReceptor.h"
#include "CPrinter.h"
#include "StringUtils.h"
#include "ProcessAux.h"

using ipc::CPrinter;
using ipc::MessageQueue;
using ipc::SharedMemory2;
using ipc::Semaphore;
using ipc::Sequence;

int main ()
{
    std::string nombreAgente;
    std::ifstream file( "canales.dsm" );

    while ( file >> nombreAgente )
    {
        if ( !nombreAgente.empty() )
        {
            try
            {
                MessageQueue<PedidoDSM>::destroy( "/tmp/" + nombreAgente   + "shm.ipc", COLA_PEDIDO_HOST  );
            }
            catch( ... )
            {

            }

            try
            {
                MessageQueue<TokenDSM>::destroy( "/tmp/" + nombreAgente   + "shm.ipc", COLA_ENTREGA_HOST );
            }
            catch(...)
            {

            }

            try
            {
                MessageQueue<TokenDSM>::destroy( "/tmp/" + nombreAgente + "shm.ipc", COLA_LIBERAR_HOST );
            }
            catch(...)
            {

            }
        }
    }
    file.close();

    system( "rm -f canales.dsm" );
    system( "rm -f recursos.dsm" );

    MessageQueue<PedidoCreacionCanalDSM>::destroy( DSM_IPC_BASEFILE, COLA_REQUEST_CREACION );
    MessageQueue<PedidoCreacionCanalDSM>::destroy( DSM_IPC_BASEFILE, COLA_REPLY_CREACION );
    Sequence::destroy( DSM_IPC_BASEFILE, SEQ_DSM_ID_CANAL );

    std::string killCmd = "killall -9 ";
    system( ( killCmd + "dsmRequestor" ).c_str() );
    system( ( killCmd + "dsmReleaser" ).c_str() );
    system( ( killCmd + "dsm_creador_canales" ).c_str() );

    return 0;
}
